package dyy.zc.note.utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.util.Log;

import java.util.List;

import cn.bmob.v3.BmobBatch;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.bmob.v3.listener.UploadFileListener;
import dyy.zc.note.application.MyApplication;
import dyy.zc.note.bean.Classify;
import dyy.zc.note.bean.NoteInfo;
import dyy.zc.note.bean.UserInfo;
import dyy.zc.note.constant.Constants;
import dyy.zc.note.ui.activity.ChangeInfoActivity;
import dyy.zc.note.ui.activity.EditInfoActivity;
import dyy.zc.note.ui.activity.LoginActivity;
import dyy.zc.note.ui.activity.RegisterActivity;

/**
 * Created by chuan on 2017/4/11.
 */

public class BmobUtils {
    private Context context;
    public static boolean loginSuccess = false;
    private boolean registerSuccess = true;

    public BmobUtils(Context context) {
        this.context = context;
    }

    /**
     * 登录查询是否账号密码输入错误
     */
    public void queryAccount(final UserInfo account) {
        BmobQuery<UserInfo> bmobQuery = new BmobQuery<>();
        bmobQuery.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("queryAccount", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(account.getAccount()) && a.getPassword().equals(account.getPassword())) {
                            loginSuccess = true;
                            MyApplication.getInstance().saveUserInfo(a);
                            break;
                        }
                    }
                } else {
                    e.printStackTrace();
                    Log.e("queryAccount", "Failed");
                }
                ((LoginActivity) context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
            }
        });
    }

    /**
     * 找回密码
     */
    public void getBackYourAccount(final String phone, final String userPassword) {
        final BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("getBackYourAccount", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(phone)) {
                            a.setPassword(userPassword);
                            findPassword(a);
                            break;
                        }
                    }
                } else {
                    Log.e("getBackYourAccount", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新用户密码
     *
     * @param account
     */
    public void findPassword(UserInfo account) {
        account.update(account.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateAccountInfo", "ok");
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    e.printStackTrace();
                    Log.e("updateAccountInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 增加用户
     *
     * @param account
     */
    public void addUserInfo(final UserInfo account) {
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    ((RegisterActivity) context).account.setId(s);
                    updateInfo(((RegisterActivity) context).account);
                    ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    Log.e("Bmob-updateInfoFailed", e.getMessage());
                }
            }
        });
    }

    /**
     * 注册新用户验证
     *
     * @param userPhone 账号
     */
    public void registerChecked(final String userPhone) {
        BmobQuery<UserInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<UserInfo>() {
            @Override
            public void done(List<UserInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("list", list + "");
                    Log.e("registerChecked", "ok");
                    for (UserInfo a :
                            list) {
                        if (a.getAccount().equals(userPhone)) {
                            registerSuccess = false;
                            break;
                        }
                    }
                    if (!registerSuccess) {
                        ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_FAILED);
                    } else {
                        ((RegisterActivity) context).handler.sendEmptyMessage(Constants.ResultCode.REGISTER_SUCCESS);
                    }
                } else {
                    Log.e("registerChecked", e.getMessage());
                }

            }
        });
    }

    /**
     * 编辑个人信息页面需要用到的上传图片
     *
     * @param bmobFile
     * @param userInfo
     */
    public void EditInfoUpLoadFile(final BmobFile bmobFile, final UserInfo userInfo) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("EditInfoUpLoadFile", "ok");
                    userInfo.setHead(bmobFile);
                    MyApplication.getInstance().saveUserInfo(userInfo);
                    ((EditInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                } else {
                    Log.e("EditInfoUpLoadFile", e.getMessage());
                    ((EditInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.FAILED);
                }
            }
        });
    }

    /**
     * 更新用户信息----编辑个人信息页面
     *
     * @param userInfo
     */
    public void EditInfpUpdateInfo(final UserInfo userInfo) {
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("EditInfpUpdateInfo", "ok");
//                    userInfo.setNewInfo(true);
                    MyApplication.getInstance().saveUserInfo(userInfo);
                    updateInfo(userInfo);
                    ((EditInfoActivity) context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
                } else {
                    Log.e("EditInfpUpdateInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新用户信息
     *
     * @param userInfo
     */
    public void updateInfo(UserInfo userInfo) {
        userInfo.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateInfo", "ok");
                } else {
                    Log.e("updateInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 上传图片
     * @param list
     * @param bmobFile
     * @param resultCode
     * @param handler
     */
    public void upLoadImage(final List<BmobFile> list, final BmobFile bmobFile, final int resultCode, final Handler handler){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("upLoadImage", "ok");
                    list.add(bmobFile);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    Log.e("upLoadImage", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新用户信息----编辑个人信息页面
     * @param userInfo
     */
    public void ChangeUpdateInfo(final UserInfo userInfo){
        Log.e("ChangeUpdateInfo",userInfo+"*******"+userInfo.getId());
        userInfo.update(userInfo.getId(),new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("ChangeUpdateInfo","ok");
                    Log.e("sdf",userInfo.getName());
                    MyApplication.getInstance().saveUserInfo(userInfo);
                    ((ChangeInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.RESULT_SUCCESS);
                }else {
                    Log.e("ChangeUpdateInfo",e.getMessage());
                }
            }
        });
    }

    /**
     * 上传图片文件
     *
     * @param bmobFile
     */
    public void upMoRenFile(final BmobFile bmobFile, final int resultCode, final Handler handler) {
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("upMoRenFile", "ok--" + bmobFile.getFileUrl());
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("file",bmobFile);
                    Message message = new Message();
                    message.setData(bundle);
                    message.what = resultCode;
                    handler.sendMessage(message);
                } else {
                    e.printStackTrace();
                    Log.e("upMoRenFile", e.getMessage());
                }
            }
        });
    }

    /**
     * 编辑个人信息页面需要用到的上传图片
     * @param bmobFile
     * @param userInfo
     */
    public void ChangeInfoUpLoadFile(final BmobFile bmobFile, final UserInfo userInfo){
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e==null){
                    Log.e("ChangeInfoUpLoadFile","ok"+bmobFile.getFileUrl());
                    userInfo.setHead(bmobFile);
                    //MyApplication.getInstance().saveUserInfo(userInfo);
                    ((ChangeInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.SUCCESS);
                }else {
                    Log.e("ChangeInfoUpLoadFile",e.getMessage());
                    ((EditInfoActivity)context).handler.sendEmptyMessage(Constants.ResultCode.FAILED);
                }
            }
        });
    }

    public void updataUserInfo(UserInfo userInfo, final int resultCode, final Handler handler){
        userInfo.update(userInfo.getId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    handler.sendEmptyMessage(resultCode);
                    Log.e("updataUserInfo", "ok--");
                } else {
                    e.printStackTrace();
                    Log.e("updataUserInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 获取日记信息
     * @param resultCode
     * @param handler
     */
    public void getNote(final UserInfo userInfo, final List<NoteInfo> noteInfoslist, final int resultCode, final Handler handler){
        BmobQuery<NoteInfo> query = new BmobQuery<>();
        query.findObjects(new FindListener<NoteInfo>() {
            @Override
            public void done(List<NoteInfo> list, BmobException e) {
                if (e == null) {
                    noteInfoslist.clear();
                    for (NoteInfo n:list){
                        if (n.getId().equals(userInfo.getId())){
                            noteInfoslist.add(n);
                        }
                    }
                    handler.sendEmptyMessage(resultCode);
                    Log.e("getNote", "ok--");
                } else {
                    e.printStackTrace();
                    Log.e("getNote", e.getMessage());
                }
            }
        });
    }

    /**
     *  删除日记
     * @param noteInfo
     * @param resultCode
     * @param handler
     */
    public void deleteNoteInfo(NoteInfo noteInfo, final int resultCode, final Handler handler){
        noteInfo.delete(noteInfo.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    handler.sendEmptyMessage(resultCode);
                    Log.e("deleteNoteInfo", "ok--");
                } else {
                    e.printStackTrace();
                    Log.e("deleteNoteInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 同步日记---第一次登录之后
     * @param userInfo
     * @param noteInfoslist
     * @param resultCode
     * @param handler
     */
    public void syncNote(UserInfo userInfo, final List<NoteInfo> noteInfoslist, final int resultCode, final Handler handler){
        for (int i = 0;i<noteInfoslist.size();i++){
            final NoteInfo n = noteInfoslist.get(i);
            n.setId(userInfo.getId());
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    n.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                Log.e("syncNote", "ok--");
                                if (finalI == noteInfoslist.size()-1){
                                    handler.sendEmptyMessage(resultCode);
                                }
                            } else {
                                e.printStackTrace();
                                Log.e("syncNote", e.getMessage());
                            }
                        }
                    });
                }
            }).start();
        }
    }

    /**
     * 获取用户的分组
     * @param id
     * @param resultCode
     * @param handler
     */
    public void getClassify( final String id, final int resultCode, final Handler handler){
        BmobQuery<Classify> query = new BmobQuery<>();
        query.findObjects(new FindListener<Classify>() {
            @Override
            public void done(List<Classify> list, BmobException e) {
                if (e == null) {
                    Log.e("getClassify", "ok--");
                    for (Classify c:list){
                        if (c.getId().equals(id)){
                            Message message = new Message();
                            message.what = resultCode;
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("classify",c);
                            message.setData(bundle);
                            handler.sendMessage(message);
                            break;
                        }
                    }

                } else {
                    e.printStackTrace();
                    Log.e("getClassify", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新分组
     * @param classify
     * @param resultCode
     * @param handler
     */
    public void updateClassify(Classify classify,final int resultCode, final Handler handler){
        classify.update(classify.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateClassify", "ok--");
                    handler.sendEmptyMessage(resultCode);
                } else {
                    e.printStackTrace();
                    Log.e("updateClassify", e.getMessage());
                }
            }
        });
    }

    /**
     * 保存分组
     * @param classify
     * @param resultCode
     * @param handler
     */
    public void saveClassify(Classify classify,final int resultCode, final Handler handler){
        classify.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("saveClassify", "ok--");
                    handler.sendEmptyMessage(resultCode);
                } else {
                    e.printStackTrace();
                    Log.e("saveClassify", e.getMessage());
                }
            }
        });
    }

    /**
     * 保存笔记
     * @param noteInfo
     * @param resultCode
     * @param handler
     */
    public void saveNoteInfo(NoteInfo noteInfo,final int resultCode, final Handler handler){
        noteInfo.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("saveNoteInfo", "ok--");
                    handler.sendEmptyMessage(resultCode);
                } else {
                    e.printStackTrace();
                    Log.e("saveNoteInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 更新笔记
     * @param noteInfo
     * @param resultCode
     * @param handler
     */
    public void updateNoteInfo(NoteInfo noteInfo,final int resultCode, final Handler handler){
        noteInfo.update(noteInfo.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("updateNoteInfo", "ok--");
                    handler.sendEmptyMessage(resultCode);
                } else {
                    e.printStackTrace();
                    Log.e("updateNoteInfo", e.getMessage());
                }
            }
        });
    }

    /**
     * 根据类型来查找笔记
     * @param type
     * @param noteInfoList
     * @param resultCode
     * @param handler
     */
    public void getNoteInfo(String type,String id, final List<NoteInfo> noteInfoList, final int resultCode, final Handler handler){
        BmobQuery<NoteInfo> query = new BmobQuery<>();
        query.addWhereEqualTo("type",type);
        query.addWhereEqualTo("id",id);
        query.findObjects(new FindListener<NoteInfo>() {
            @Override
            public void done(List<NoteInfo> list, BmobException e) {
                if (e == null) {
                    Log.e("updateNoteInfo", "ok--");
                    noteInfoList.clear();
                    noteInfoList.addAll(list);
                    handler.sendEmptyMessage(resultCode);
                } else {
                    e.printStackTrace();
                    Log.e("updateNoteInfo", e.getMessage());
                }
            }
        });
    }
}